import request from 'request';

const ApplicationTypeHeader: string = "application/json;charset=utf-8";

// 飞书机器人API: https://open.feishu.cn/document/client-docs/bot-v3/add-custom-bot
export class FeishuBot {
    private readonly _webhookUrl: string;
    constructor(webhookUrl: string) {
        this._webhookUrl = webhookUrl;
    }

    public pushMsgMarkdown(msg: string, title: string, atUser?: Array<string>): boolean {
        try {
            let finalMsg = msg;
            // 处理 at 手机号 
            const mobiles = atUser || [];
            if (mobiles.length > 0) {
                // 飞书的 
                const atText = mobiles.map(openId => `<at id="${openId}">Name</at>`).join(' ');
                const messageWithAt = `${msg}\n\n${atText}`;
                finalMsg = messageWithAt;
            }

            let options: request.CoreOptions = {
                headers: {
                    "Content-Type": ApplicationTypeHeader
                },
                json: {
                    "msg_type": "interactive",
                    "card": {
                        "schema": "2.0",
                        "config": {
                            "update_multi": true,
                            "style": {
                                "text_size": {
                                    "normal_v2": {
                                        "default": "normal",
                                        "pc": "normal",
                                        "mobile": "heading"
                                    }
                                }
                            }
                        },
                        "body": {
                            "direction": "vertical",
                            "padding": "12px 12px 12px 12px",
                            "elements": [
                                {
                                    "tag": "markdown",
                                    "content": `${finalMsg}`,
                                    "text_align": "left",
                                    "text_size": "normal_v2",
                                    "margin": "0px 0px 0px 0px"
                                },
                                // {
                                //     "tag": "button",
                                //     "text": {
                                //         "tag": "plain_text",
                                //         "content": "🌞更多景点介绍"
                                //     },
                                //     "type": "default",
                                //     "width": "default",
                                //     "size": "medium",
                                //     "behaviors": [
                                //         {
                                //             "type": "open_url",
                                //             "default_url": "https://baike.baidu.com/item/%E8%A5%BF%E6%B9%96/4668821",
                                //             "pc_url": "",
                                //             "ios_url": "",
                                //             "android_url": ""
                                //         }
                                //     ],
                                //     "margin": "0px 0px 0px 0px"
                                // }
                            ]
                        },
                        "header": {
                            "title": {
                                "tag": "plain_text",
                                "content": `${title}`,
                            },
                            "subtitle": {
                                "tag": "plain_text",
                                "content": ""
                            },
                            "template": "blue",
                            "padding": "12px 12px 12px 12px"
                        }
                    }
                }
            };

            request.post(this._webhookUrl, options, function (error, response, body) {
                console.log("飞书机器人请求错误信息:", error ? JSON.stringify(error) : "无错误");
                console.log("飞书机器人响应状态:", response ? `状态码: ${response.statusCode}, 状态信息: ${response.statusMessage}` : "无响应");
                console.log("飞书机器人响应体:", typeof body === 'object' ? JSON.stringify(body, null, 2) : body);
                console.debug(`push msg ${finalMsg}, response: ${JSON.stringify(body)}`);
            });
        }
        catch (err) {
            console.error(err);
            return false;
        }
        return true;
    }

    public pushMsgText(msg: string, atMobiles?: Array<string>): boolean {
        try {
            let finalMsg = msg;
            // 处理 at 手机号
            const mobiles = atMobiles || [];
            if (mobiles.length > 0) {
                // 在消息末尾添加 @ 标记
                const atText = mobiles.map(mobile => `@${mobile}`).join(' ');
                finalMsg = `${msg}\n\n${atText}`;
            }

            let options: request.CoreOptions = {
                headers: {
                    "Content-Type": ApplicationTypeHeader
                },
                json: {
                    "msg_type": "text",
                    "content": {
                        "text": finalMsg
                    }
                }
            };

            request.post(this._webhookUrl, options, function (error, response, body) {
                console.debug(`push msg ${msg}, response: ${JSON.stringify(body)}`);
            });
        }
        catch (err) {
            console.error(err);
            return false;
        }
        return true;
    }

    // 飞书特有的富文本消息方法
    public pushRichText(title: string, content: string, atMobiles?: Array<string>): boolean {
        try {
            let finalContent = content;
            const mobiles = atMobiles || [];
            if (mobiles.length > 0) {
                const atText = mobiles.map(mobile => `@${mobile}`).join(' ');
                finalContent = `${content}\n\n${atText}`;
            }

            let options: request.CoreOptions = {
                headers: {
                    "Content-Type": ApplicationTypeHeader
                },
                json: {
                    "msg_type": "rich_text",
                    "content": {
                        "rich_text": {
                            "elements": [
                                {
                                    "tag": "p",
                                    "elements": [
                                        {
                                            "tag": "text",
                                            "text": title,
                                            "style": {
                                                "bold": true
                                            }
                                        }
                                    ]
                                },
                                {
                                    "tag": "p",
                                    "elements": [
                                        {
                                            "tag": "text",
                                            "text": finalContent
                                        }
                                    ]
                                }
                            ]
                        }
                    }
                }
            };

            request.post(this._webhookUrl, options, function (error, response, body) {
                console.debug(`push rich text msg ${title}: ${finalContent}, response: ${JSON.stringify(body)}`);
            });
        }
        catch (err) {
            console.error(err);
            return false;
        }
        return true;
    }
}